<?php

namespace catchAdmin\api\controller;

use cainiao\api\v1\Link;
use catchAdmin\customs\model\CnOrder;
use catcher\CatchResponse;
use catcher\Code;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use think\helper\Str;
use think\Request;
/*
 * 菜鸟仓库
 * */
class Cainiao extends Index
{

    public function cainiaoService(Request $request)
    {

        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('CaiNiao',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token

            if(!$request->has('data','post')){
                return $this->commonReturn('CaiNiao',['code'=>Code::FAILED, 'msg'=>'缺少data']);
            }

            //处理data
            $data = json_decode($data,true);
            if(!$data||!is_array($data)){
                return $this->commonReturn('CaiNiao',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
            }

            //方法分发
            switch ($serviceType)
            {
                //提交订单
                case 'submitOrder':
                    $result = $this->submitOrder($data);
                    break;
                //查询订单
                case 'queryOrder':
                    $result = $this->queryOrder($data);
                    break;
                //修改订单
                case 'modifyOrder':
                    $result = $this->modifyOrder($data);
                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn("CaiNiao:" . $serviceType,$result);

        } catch (\Exception $exception) {
            return $this->commonReturn("CaiNiao:" . $serviceType,['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }

    }

    //提交订单
    protected function submitOrder($data)
    {
        $keys = [
            'ownerUserId',
            'businessUnitId',
            'orderType',
            'storeCode',
            'externalShopName',
            'orderSource',
            'orderCreateTime',
            'orderPayTime',
            'saleMode',
            'receiverInfo',
            'senderInfo',
            'refunderInfo',
            'goodsTotalPrice',
            'coupon',
            'insurance',
            'postFee',
            'orderAmountInfo',
            'customsDeclareInfo',
            'businessUnitId',
            'externalOrderCode'
        ];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数

        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }


        $order  = (new CnOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('externalOrderCode',$data['externalOrderCode'])
            ->find();

        if($order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['externalOrderCode']}已存在"];
        }

        ///计算参数
        $goodsTotalPrice = $data['goodsTotalPrice'];//商品总价，申报金额
        $coupon = $data['coupon'];//优惠金额
        $insurance = $data['insurance'];//保险费
        $postFee = $data['postFee'];//运费

        $dutiablePrice = dutiablePrice($insurance,$postFee,$goodsTotalPrice) ;//订单完税总价
        $customsTax = customsTax($dutiablePrice ,0,1);//关税
        $consumptionTax = consumptionTax($dutiablePrice,$customsTax,0.091,1);//消费税金额
        $vat = vat($dutiablePrice,$customsTax,$consumptionTax,0,1);//增值税
        $totalTax = totalTax($customsTax,$consumptionTax,$vat);//综合税
        $actualPayment = actualPayment($dutiablePrice,$totalTax,$coupon);//消费者实付金额

        $data['orderAmountInfo'] = [
            'dutiablePrice'=>priceFormat($dutiablePrice),//订单完税总价
            'coupon'=>priceFormat($coupon),//优惠金额
            'consumptionTax'=>priceFormat($consumptionTax),//消费税金额
            'postFee'=>priceFormat($postFee),//运费
            'vat'=>priceFormat($vat),//增值税
            'customsTax'=>priceFormat($customsTax),//关税
            'actualPayment'=> priceFormat($actualPayment),
            'totalTax'=>priceFormat($totalTax),
            'insurance'=>priceFormat($insurance),
            'currency'=>'CNY'
        ];//订单金额信息

        //$this->content['externalOrderCode'] = Str::random(20,1);

        foreach ($data['orderItemList'] as $key => &$value){
            $temp = [];
            $temp['itemId'] = $value['itemId'];
            $temp['itemQuantity'] = $value['itemQuantity'];
            $temp['totalPrice'] = $value['totalPrice'];//商品申报货值
            $temp['itemTotalActualPrice'] = $value['itemTotalActualPrice'];//商品总价 优惠后
            $temp['itemTotalPrice'] = $value['itemTotalPrice'];//商品总价 优惠前

            $dutiablePrice = dutiablePrice(0,0,$temp['totalPrice']) ;//订单完税总价
            $customsTax = customsTax($dutiablePrice ,0,1);//关税
            $consumptionTax = consumptionTax($dutiablePrice,$customsTax,0.091,1);//消费税金额
            $vat = vat($dutiablePrice,$customsTax,$consumptionTax,0,1);//增值税
            $totalTax = totalTax($customsTax,$consumptionTax,$vat);//综合税

            $value['declareInfo']= [
                'customsTax'=>priceFormat($customsTax),//商品关税
                'consumptionTax'=>priceFormat($consumptionTax),//商品消费税
                'totalTax'=>priceFormat($totalTax),//商品综合税
                'itemTotalActualPrice'=>priceFormat($temp['itemTotalActualPrice']),//商品总价优惠后
                'itemTotalPrice'=>priceFormat($temp['itemTotalPrice']),//商品总价优惠前
                'vat'=>$vat
            ];
            unset($data['orderItemList'][$key]['totalPrice'],$data['orderItemList'][$key]['itemTotalActualPrice'],$data['orderItemList'][$key]['itemTotalPrice']);
            //$value = $temp;
        }
//        $data['externalOrderCode'] = Str::random(20,1);

        unset($data['goodsTotalPrice']);
        unset($data['coupon']);
        unset($data['insurance']);
        unset($data['postFee']);


        $data['receiverInfo'] =   array_key_exists('receiverInfo',$data) ? json_encode($data['receiverInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['senderInfo'] =  array_key_exists('senderInfo',$data) ? json_encode($data['senderInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['refunderInfo'] =  array_key_exists('refunderInfo',$data) ? json_encode($data['refunderInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['orderAmountInfo'] =  array_key_exists('orderAmountInfo',$data) ? json_encode($data['orderAmountInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['customsDeclareInfo'] =  array_key_exists('customsDeclareInfo',$data) ? json_encode($data['customsDeclareInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['orderItemList'] =  array_key_exists('orderItemList',$data) ? json_encode($data['orderItemList'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        //
        $data['extendFields'] =   array_key_exists('extendFields',$data)   ? json_encode($data['extendFields'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['departureInfo'] =   array_key_exists('departureInfo',$data)  ? json_encode($data['departureInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['logisticsServices'] =   array_key_exists('logisticsServices',$data)  ? json_encode($data['logisticsServices'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['packageInfo'] =   array_key_exists('packageInfo',$data)  ? json_encode($data['packageInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        //
        $data['_ext_data'] = json_encode($data);
        $data['tenant_id'] =  $this->merchantInfo['tenant_id'];

        Db::startTrans();
        try {
            $model = new CnOrder();
            $model->save($data);

            // 提交事务
            Db::commit();
            return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
        } catch (\Exception $e) {
            Db::rollback();
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }



    }

    //查询订单物流详情查询接口
    protected function queryOrder($data){
        $keys = ['userId','lgOrderCode'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数

        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_LOGISTICS_DETAIL_QUERY($data);

            return [ 'code'=>Code::SUCCESS , 'msg'=> '查询成功' , 'data'=>$result];
        } catch (\Exception $e) {

            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }

    //修改订单 国际订单信息修改
    protected function modifyOrder($data){
        $keys = ['buyerName','buyerIDNo','payType','payOrderId','cnOrderCode'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数

        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_ORDER_INFO_MODIFY($data);

            return [ 'code'=>Code::SUCCESS , 'msg'=> '修改成功' , 'data'=>$result];
        } catch (\Exception $e) {

            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }
}